<template>
  <section class="main" v-loading="resultObj.loading">
    <template v-if="locale == 'en'">
      <BuyEn :data="resultObj.data" @log="addLog" />
    </template>
    <template v-else-if="locale == 'zh-cn'">
      <BuyZhcn :data="resultObj.data" @log="addLog" />
    </template>
  </section>
</template>

<script lang="ts" setup name="HomePage">
  import { computed, onMounted, nextTick } from 'vue';
  import { useUserStore } from '@/store/modules/user';
  import { setLang } from '@/i18n';
  import { useI18n } from 'vue-i18n';
  import { goodsApi, logApi } from '@/api/index';
  import type { FormInstance, FormRules } from 'element-plus';
  import BuyEn from './components/buy/en.vue';
  import BuyZhcn from './components/buy/zh-cn.vue';

  const { locale } = useI18n();

  const userStore = useUserStore();

  const getUserInfo = computed(() => {
    let userInfo = userStore.getUserInfo || {};
    return userInfo;
  });

  const resultObj = reactive({
    data: [],
    loading: false,
  });

  const getGoods = async () => {
    if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.data = [];
    goodsApi({
      lang: locale.value,
    })
      .then((res) => {
        if (res.data) {
          for (let i in res.data) {
            resultObj.data.push({
              goods_id: res.data[i].id,
              pay_way: 'alipay',
              ...res.data[i],
            });
          }
        }
        resultObj.loading = false;
        swiperInstance();
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const addLog = async (item) => {
    logApi({
      goods_id: item.id,
    })
      .then(() => {
        console.log('立即购买');
      })
      .catch((err) => {
        console.log('err', err);
      });
  };
  
  // swiper实例
  const swiperInstance = () => {
    nextTick(() =>{
      var swiper = new Swiper('.swiper-container', {
        pagination: '.swiper-pagination',
        paginationClickable: true,
        nextButton: '.swiper-button-next',
        prevButton: '.swiper-button-prev',
        slidesPerView: 4.4,
        paginationClickable: true,
        spaceBetween: 20,
        autoplay: 3000,
      });
    })
  };

  watch(
    () => locale.value,
    () => {
      getGoods();
    },
    { deep: true, immediate: true },
  );

  onMounted(() => {
    getGoods();
  });
</script>
<style lang="scss">
  .main {
    min-height: calc(100vh - 148px);
  }
</style>
